package com.ibp.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;

import com.github.pagehelper.StringUtil;
import com.ibp.controller.SysRunManageController;
import com.ibp.service.DictDataService;
import com.ibp.service.ExecuteCmdService;
import com.ibp.service.FSHttpService;
import com.ibp.service.LogNodeService;
import com.ibp.utils.PropertyUtils;
import com.ibp.utils.SocketClientUtils;

@Service("logNodeServiceImpl")
public class LogNodeServiceImpl implements LogNodeService,InitializingBean {

	private static Logger logger = LoggerFactory.getLogger(SysRunManageController.class);

	private String iblog_ip = null;
	private String iblog_port = null;
	private String url = null;
	private String iblogCmd_ip = null;
	private String iblogCmd_port = null;
	private ServletContext servletContext;

	@Autowired
	PropertyUtils propertyUtils;
	@Autowired
	FSHttpService fSHttpServiceImpl;
	@Autowired
	DictDataService dictDataServiceImpl;
	@Autowired
	ExecuteCmdService executeCmdServiceImpl;
	  

	/**
	 * 返回日志归集节点状态
	 */
	@Override
	public Map<String,Object> getLogNode(String cmd) {
		Map<String,Object> map = new HashMap<String,Object>();
		String response = executeCmdServiceImpl.executeIblogCmdData(cmd);
		map.put("address", this.iblogCmd_ip+":"+this.iblogCmd_port);
		map.put("status", getStatus("iblog.sh status \n"));
		map.put("console",response);
		return map;
	}
	
	/***
	 * 返回服务状态
	 * @param response
	 * @return
	 */
	private boolean getStatus(String cmd){
		return executeCmdServiceImpl.executeIblogCmd(cmd);
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public void afterPropertiesSet() throws Exception {
		this.servletContext = dictDataServiceImpl.getServletContext();
		logger.info("初始化日志节点ip和port配置,servletContext:"+servletContext); 
		Map<String,Map<String,String>> dictMap = (Map<String, Map<String, String>>) servletContext.getAttribute("dictMap");
		this.iblog_ip  = 	dictMap.get("http.iblog").get("ip");
		this.iblog_port= 	dictMap.get("http.iblog").get("port");
	    this.iblogCmd_ip = 	dictMap.get("tcp.iblog").get("ip");
		this.iblogCmd_port = dictMap.get("tcp.iblog").get("port") ;
	    this.url = this.iblog_ip+":"+this.iblog_port;
	    
	}

}
